package com.networklib.http.impl;

import com.networklib.http.HTTP;
import com.networklib.http.IHttpRequest;
import com.networklib.http.exception.NetException;
import com.networklib.http.interceptor.DownloadProgressInterceptor;
import com.networklib.http.interceptor.UploadProgressInterceptor;
import com.networklib.http.other.MimeType;

import java.io.File;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;

/**
 * Created by ASUS on 2017/6/13.
 */

public abstract class BaseHttpRequestImpl implements IHttpRequest {
    protected ProgressRequestBodyImpl.ProgressListener onProgressListener;
    protected String url;

    protected OkHttpClient client;

    public BaseHttpRequestImpl(String url) throws NetException {
        this.url = url;
        client = HTTP.getInstance().getHttp();
    }


    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    protected RequestBody getRequestBody(Object value, ProgressRequestBodyImpl.ProgressListener listener) {
        return getRequestBody(value, null, listener);
    }

    protected RequestBody getRequestBody(Object value, MediaType mediaType, ProgressRequestBodyImpl.ProgressListener listener) {
        RequestBody body = null;
        if (value instanceof File) {
            body = RequestBody.create(mediaType != null ? mediaType : MimeType.FILE.getMediaType(), (File) value);
        } else if (value instanceof String) {
            body = RequestBody.create(mediaType != null ? mediaType : MimeType.JSON.getMediaType(), (String) value);
        } else if (value instanceof byte[]) {
            body = RequestBody.create(mediaType != null ? mediaType : MimeType.JSON.getMediaType(), (byte[]) value);
        }
        return new ProgressRequestBodyImpl(body, listener);
    }

    public void setOnProgressListener(ProgressRequestBodyImpl.ProgressListener onProgressListener) {
        this.onProgressListener = onProgressListener;
    }
    public void setOnProgressListener(ProgressRequestBodyImpl.ProgressListener upProgressListener, ProgressResponseBodyImpl.ProgressListener downProgressListener) {
        if(upProgressListener != null) {
            this.client.interceptors().add(new UploadProgressInterceptor(upProgressListener));
        }

        if(downProgressListener != null) {
            this.client.interceptors().add(new DownloadProgressInterceptor(downProgressListener));
        }

    }
}
